package com.haiqiu.common.utils.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import com.haiqiu.common.result.Constants;
import com.haiqiu.common.utils.tools.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

/**
 * @author : haiqiu
 * @date ：2021/1/5 17:32
 * @description: Servlet工具类
 */
@Component
@Data
public class ServletUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServletUtil.class);

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.authorization}")
    private String authorization;

    @Value("${jwt.header}")
    private String header;

    private final static String ENCODING = "UTF-8";
    private final static String TAO_BAO_IP = "https://ip.taobao.com/outGetIpInfo";


    /**
     * 获取前端访问设备的ip
     *
     * @return 设备的ip
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    /**
     * 通过IP获取地址(需要联网，调用淘宝的IP库)
     *
     * @param ip
     * @return
     */
    public static String getAddress(String ip) {
        String address = null;
        Map<String,String> params = new HashMap<>();
        params.put("ip", ip);
        params.put("accessKey", "alibaba-inc");
        String result = HttpUtil.request(TAO_BAO_IP, "POST", ENCODING, null, params, 5000, 5000);
        JSONObject jsonObject = com.alibaba.fastjson.JSON.parseObject(result);
        if (Integer.parseInt(jsonObject.getString("code"))==0){
            String data = jsonObject.getString("data");
            address = JSON.parseObject(data).getString("country") +
                    "-" + JSON.parseObject(data).getString("region") +
                    "-" + JSON.parseObject(data).getString("city") +
                    " " + JSON.parseObject(data).getString("isp");
        }
        return address;
    }


    /**
     * 获取本机的操作系统
     * @return 操作系统
     */
    public static String getLocalOs() {
        //系统属性
        Properties props = System.getProperties();
        //System.out.println("操作系统的名称：" + props.getProperty("os.name"));
        String os = props.getProperty("os.name");
        if (os.contains(Constants.WINDOWS)){
            return Constants.WINDOWS;
        }else {
            return Constants.LINUX;
        }
    }

    /**
     * 获取客户端系统os
     *
     * @return os
     */
    public static String getOs() {
        return getOs(ServletUtil.getHttpServletRequest());
    }
    public static String getOs(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == "" || userAgent == null) {
            userAgent = "";
        }
        if (userAgent.contains("Windows")) {
            if (userAgent.contains("Windows NT 10.0")) {
                return "Windows 10";
            } else if (userAgent.contains("Windows NT 6.2")) {
                return "Windows 8";
            } else if (userAgent.contains("Windows NT 6.1")) {
                return "Windows 7";
            } else if (userAgent.contains("Windows NT 6.0")) {
                return "Windows Vista";
            } else if (userAgent.contains("Windows NT 5.2")) {
                return "Windows XP";
            } else if (userAgent.contains("Windows NT 5.1")) {
                return "Windows XP";
            } else if (userAgent.contains("Windows NT 5.01")) {
                return "Windows 2000";
            } else if (userAgent.contains("Windows NT 5.0")) {
                return "Windows 2000";
            } else if (userAgent.contains("Windows NT 4.0")) {
                return "Windows NT 4.0";
            } else if (userAgent.contains("Windows 98; Win 9x 4.90")) {
                return "Windows ME";
            } else if (userAgent.contains("Windows 98")) {
                return "Windows 98";
            } else if (userAgent.contains("Windows 95")) {
                return "Windows 95";
            } else if (userAgent.contains("Windows CE")) {
                return "Windows CE";
            }
        } else if (userAgent.contains("Mac OS X")) {
            if (userAgent.contains("iPhone")) {
                return "iPhone";
            } else if (userAgent.contains("iPad")) {
                return "iPad";
            } else {
                return "Mac";
            }
        } else if (userAgent.contains("Android")) {
            return "Android";
        } else if (userAgent.contains("Linux")) {
            return "Linux";
        } else if (userAgent.contains("FreeBSD")) {
            return "FreeBSD";
        } else if (userAgent.contains("Solaris")) {
            return "Solaris";
        }
        return "其他";
    }


    /**
     * 获取浏览器
     * @param request
     * @return
     */
    public static String getBrowser(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == "" || userAgent == null) {
            userAgent = "";
        }
        if (userAgent.contains("Edg")) {
            return "Microsoft Edge";
        } else if (userAgent.contains("QQBrowser")) {
            return "QQ浏览器";
        }
        else if (userAgent.contains("Chrome") && userAgent.contains("Safari")) {
            return "Chrome";
        } else if (userAgent.contains("Firefox")) {
            return "Firefox";
        } else if (userAgent.contains("360")) {
            return "360浏览器";
        } else if (userAgent.contains("Opera")) {
            return "Opera";
        } else if (userAgent.contains("Safari") && !userAgent.contains("Chrome")) {
            return "Safari";
        } else if (userAgent.contains("MetaSr1.0")) {
            return "搜狗浏览器";
        } else if (userAgent.contains("TencentTraveler")) {
            return "腾讯浏览器";
        } else if (userAgent.contains("UC")) {
            return "UC浏览器";
        } else if (userAgent.contains("MSIE")) {
            if (userAgent.contains("MSIE 10.0")) {
                return "IE 10";
            } else if (userAgent.contains("MSIE 9.0")) {
                return "IE 9";
            } else if (userAgent.contains("MSIE 8.0")) {
                return "IE 8";
            } else if (userAgent.contains("MSIE 7.0")) {
                return "IE 7";
            } else if (userAgent.contains("MSIE 6.0")) {
                return "IE 6";
            }else if (userAgent.contains("Trident/7.0")) {
                return "IE 11";
            }
        } else {
            return "其他";
        }
        return "其他";
    }


    public boolean isLocalHost(String ip) {
        return "127.0.0.1".equals(ip) || "localhost".equals(ip);
    }


    /**
     * 获取客户端的request数据
     *
     * @return
     */
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 获取用户名
     *
     * @return 用户名
     */
    public String getUserName() {
        return jwtTokenUtil.getUsername(getHttpServletRequest());
    }

    /**
     * 获取token
     *
     * @return token
     */
    public String getToken() {
        return jwtTokenUtil.getToken(getHttpServletRequest());
    }



    public static HttpServletResponse getHttpServletResponse() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
    }





}
